package com.laundry.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FileUploadService {
    
    @Value("${file.upload.dir:uploads/}")
    private String uploadDir;
    
    public String uploadFile(MultipartFile file, String type) {
        try {
            // 验证文件
            validateFile(file, type);
            
            // 创建上传目录
            Path uploadPath = createUploadDirectory(type);
            
            // 生成文件名
            String fileName = generateFileName(file.getOriginalFilename());
            
            // 保存文件
            Path filePath = uploadPath.resolve(fileName);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 返回文件访问路径
            return "/" + type + "/" + fileName;
            
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
    
    public List<String> uploadFiles(List<MultipartFile> files, String type) {
        List<String> filePaths = new ArrayList<>();
        
        for (MultipartFile file : files) {
            String filePath = uploadFile(file, type);
            filePaths.add(filePath);
        }
        
        return filePaths;
    }
    
    private void validateFile(MultipartFile file, String type) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        // 验证文件大小（10MB）
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new RuntimeException("文件大小不能超过10MB");
        }
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null) {
            throw new RuntimeException("无法确定文件类型");
        }
        
        switch (type) {
            case "image":
                if (!contentType.startsWith("image/")) {
                    throw new RuntimeException("只允许上传图片文件");
                }
                break;
            case "document":
                if (!contentType.equals("application/pdf") && 
                    !contentType.equals("application/msword") &&
                    !contentType.equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
                    throw new RuntimeException("只允许上传PDF或Word文档");
                }
                break;
            default:
                // 允许所有类型
                break;
        }
    }
    
    private Path createUploadDirectory(String type) throws IOException {
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        Path uploadPath = Paths.get(uploadDir, type, dateStr);
        
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        return uploadPath;
    }
    
    private String generateFileName(String originalFilename) {
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        
        return UUID.randomUUID().toString() + extension;
    }
}
